package cn.lg.soar.system.biz.modules.auth.service;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.system.biz.modules.auth.entity.UserRoleRel;
import cn.lg.soar.system.biz.modules.auth.mapper.UserRoleRelMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import static cn.lg.soar.system.biz.config.SystemCacheKey.USERID_TO_ALL_ROLEIDS;
import static cn.lg.soar.system.biz.config.SystemCacheKey.USERID_TO_ROLEIDS;

/**
 * @author luguoxiang
 * @date 2022/4/10
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class UserRoleRelService extends ServiceImpl<UserRoleRelMapper, UserRoleRel> {

    /**
     * 根据用户Id获取角色
     * @param userId
     * @return
     */
    @Cacheable(value = USERID_TO_ROLEIDS, key = "#p0", cacheManager = "remote")
    public List<Long> getRoleIds(Long userId) {
        return listObjs(
                Wrappers.<UserRoleRel>lambdaQuery()
                        .select(UserRoleRel::getRoleId)
                        .eq(UserRoleRel::getUserId, userId),
                x -> Long.parseLong(x.toString())
        );
    }

    /**
     * 设置用户角色
     * @param userId
     * @param roleIds
     */
    @CacheEvict(value = { USERID_TO_ROLEIDS, USERID_TO_ALL_ROLEIDS }, key = "#p0")
    @Transactional(rollbackFor = RuntimeException.class)
    public void setUserRole(Long userId, Collection<Long> roleIds) {
        // 清空旧值
        clearByUser(userId);
        // 批量保存新值
        if (CollectionUtils.isEmpty(roleIds)) {
            return;
        }
        List<UserRoleRel> collect = roleIds.stream()
                .distinct()
                .map(x -> {
                    UserRoleRel data = new UserRoleRel();
                    data.setUserId(userId);
                    data.setRoleId(x);
                    return data;
                })
                .collect(Collectors.toList());
        AssertUtil.isTrue(saveBatch(collect), "保存用户角色失败");
    }

    @CacheEvict(value = { USERID_TO_ROLEIDS, USERID_TO_ALL_ROLEIDS }, key = "#p0")
    public void clearByUser(Long userId) {
        this.remove(Wrappers.<UserRoleRel>lambdaQuery().eq(UserRoleRel::getUserId, userId));
    }

    public void clearByRole(Long roleId) {
        this.remove(Wrappers.<UserRoleRel>lambdaQuery().eq(UserRoleRel::getRoleId, roleId));
    }
}
